//
//  MYComposeViewController.swift
//  NewMicroblog
//
//  Created by apple on 2016/10/31.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import pop


class MYComposeView: UIView {
    
    /// 按钮数组
    var composeButtonArray:[UIButton] = [UIButton]();
    var target: UIViewController?
    ///plist文件数据
    fileprivate lazy var composePlistArray: [MYComposeModel] = self.loadComposeData()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        size = CGSize(width: SCREENWIDTH, height: SCREENHEIGHT)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 设置界面的UI
    func setupUI(){
//       backgroundColor = UIColor.white
        addSubview(bgImgV);
        addSubview(sloganView)
        sloganView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        addChildButton()
        buttonPopAnimation(isUp: true)
    }
    ///截取屏幕上的图片
    func getScreenShot() -> UIImage{
        let window = UIApplication.shared.keyWindow!
        //开启图形上下文
       UIGraphicsBeginImageContext((window.size))
      let rect = CGRect(origin: CGPoint.zero, size: window.size)
        window.drawHierarchy(in: rect, afterScreenUpdates: false)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
     }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        buttonPopAnimation(isUp: false)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute: {
            self.removeFromSuperview()
        })
    }
    //子控件
    fileprivate lazy var bgImgV: UIImageView = {
        
         let  image = self.getScreenShot().applyLightEffect()
        
        let imagV = UIImageView(image: image)
    
        return imagV
    }()
    fileprivate lazy var sloganView: UIImageView = UIImageView(imageName: "compose_slogan")
    
    /// 添加6个按钮
    private func addChildButton(){
        let btnWidth: CGFloat = 80
        let btnheight: CGFloat = 110
        let btnMargin:CGFloat = (width - 3 * btnWidth) / 4
        for i  in 0..<6 {
            let col = i % 3
            let row = i / 3
            let model = self.composePlistArray[i]
            let btn = MYComposemenuBtn(setImage: model.icon, title: model.title, tagart: self, action: #selector(bntClick(btn:)))
            btn.size = CGSize(width: btnWidth, height: btnheight)
            btn.x = CGFloat(col) * btnWidth + CGFloat(col + 1) * btnMargin
            btn.y = CGFloat(row) * btnMargin + CGFloat(row) * btnheight + SCREENHEIGHT
            btn.tag = i
            addSubview(btn)
            self.composeButtonArray.append(btn);
            
        }
    }
    
    /// 按钮pop动画
    fileprivate func buttonPopAnimation(isUp:Bool){
        if isUp == false {
            self.composeButtonArray = self.composeButtonArray.reversed()
        }
        for (i, button) in self.composeButtonArray.enumerated(){
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            if isUp {
                animation?.toValue = NSValue(cgPoint: CGPoint(x: button.centerX, y: button.centerY - 350))
            }else{
                 animation?.toValue = NSValue(cgPoint: CGPoint(x: button.centerX, y: button.centerY + 350))
            }
            animation?.springBounciness = 10
            animation?.springSpeed = 10
            animation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            button.pop_add(animation, forKey: nil)
        }
    }
    
    func show(target:UIViewController){
        self.target = target;
        target.view.addSubview(self);
        
    }
    
    
    
    //MARK:- 点击菜单按钮操作
    @objc private func bntClick(btn:UIButton){
        UIView.animate(withDuration: 0.25, animations:{
            for button in self.composeButtonArray{
                button.alpha = 0.2
                if button == btn{
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else{
                    button.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
                }
            }
        }){ (_) in
            UIView.animate(withDuration: 0.25, animations: { 
                for button in self.composeButtonArray{
                    button.alpha = 1
                    button.transform = CGAffineTransform.identity
                }
            }, completion: { (_) in
                //弹出控制器
                let model = self.composePlistArray[btn.tag]
                let classType = NSClassFromString(model.className!) as! UIViewController.Type
                let vc = classType.init()
                let nav = UINavigationController(rootViewController: vc)
                self.target?.present(nav, animated: true, completion: {
                    self.removeFromSuperview()
                })
            })
        }
    }
    
    /// 加载plist文件
    ///
    /// - Returns: 数组
    fileprivate func loadComposeData() -> [MYComposeModel]{
        let filePath = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let  dataArr = NSArray(contentsOfFile: filePath)!
        let modelArr = NSArray.yy_modelArray(with: MYComposeModel.self, json: dataArr) as! [MYComposeModel]
        return modelArr
    }
    
}
